﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Framework;
using VAdvantage.Controls;
using VAdvantage.Model;
using VAdvantage.Utility;
using VAdvantage.Classes;
using System.Text;
using System.Data.SqlClient;
using System.Linq;

namespace VAdvantage.Search
{
    public class InfoPayment : Info
    {
        #region Private variables
        string _queryValue = "";
        int bp;
        private ToolTip tooltip = new ToolTip();
        //on value change of datetime pickker
        private bool _dateTimeFromCheck = false;
        private bool _dateTimeToCheck = false;
        //on Amount text change value
        private bool _AmtFromCheck = false;
        private bool _AmtToCheck = false;
        private Logging.VLogger log = Logging.VLogger.GetVLogger(typeof(MOrderLine).FullName);
        //  Static Info
        private VLabel lblDocumentNo = new VLabel();
        private VLabel lblBPartner_ID = new VLabel();
        private VLabel lblDateFrom = new VLabel();
        private VLabel lblDateTo = new VLabel();
        private VLabel lblAmtFrom = new VLabel();
        private VLabel lblAmtTo = new VLabel();

        private VTextBox txtDocumentNo = new VTextBox(HEIGHT);
        private VTextBoxButton vBPartner_ID;
        private VAdvantage.Controls.VDatePicker dtpDateFrom = new VAdvantage.Controls.VDatePicker();
        private VAdvantage.Controls.VDatePicker dtpDateTo = new VAdvantage.Controls.VDatePicker();
        private VNumTextBox txtAmtFrom = new VNumTextBox();
        private VNumTextBox txtAmtTo = new VNumTextBox();
        private VCheckBox chkIsReceipt = new VCheckBox();

        //  Array of Column Info    
        private static Info_Column[] _paymentLayout = {
		new Info_Column("C_Payment_ID", "p.C_Payment_ID", typeof(IDColumn)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "C_BankAccount_ID"),
			"(SELECT b.Name || ' ' || ba.AccountNo FROM C_Bank b, C_BankAccount ba WHERE b.C_Bank_ID=ba.C_Bank_ID AND ba.C_BankAccount_ID=p.C_BankAccount_ID)", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "C_BPartner_ID"),
			"(SELECT Name FROM C_BPartner bp WHERE bp.C_BPartner_ID=p.C_BPartner_ID)", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "DateTrx"),
			"p.DateTrx", typeof(DateTime)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "DocumentNo"),
			"p.DocumentNo", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "IsReceipt"),
			"p.IsReceipt", typeof(Boolean)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "C_Currency_ID"),
			"(SELECT ISO_Code FROM C_Currency c WHERE c.C_Currency_ID=p.C_Currency_ID)", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "PayAmt"),
			"p.PayAmt",  typeof(Decimal)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "ConvertedAmount"),
			"currencyBase(p.PayAmt,p.C_Currency_ID,p.DateTrx, p.AD_Client_ID,p.AD_Org_ID)", typeof(Decimal)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "DiscountAmt"),
			"p.DiscountAmt",  typeof(Decimal)),
		new Info_Column((Msg.Translate(Envs.GetContext(), "WriteOffAmt")).Replace("-"," "),
			"p.WriteOffAmt",  typeof(Decimal)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "IsAllocated"),
			"p.IsAllocated",  typeof(Boolean))
	};

        #endregion


        public InfoPayment(Object frame, bool modal, int WindowNo, String value, bool multiSelection, String whereClause)
            : base(frame, modal, WindowNo, "p", "C_Payment_ID", multiSelection, whereClause)
        {
            _queryValue = value;
            log.Info("InfoPayment");
            base.SetTitle(Msg.GetMsg(Envs.GetContext(), "InfoPayment", true));
            try
            {
                StatInit();
                InitInfo();
            }
            catch
            {
                return;
            }
            //

        }

        /// <summary>
        /// Get Layout
        /// </summary>
        /// <returns>array of Column_Info</returns>
        protected override Info_Column[] GetInfoColumns()
        {
            return _paymentLayout;
        }

        private void StatInit()
        {
            Context ctx = Envs.GetContext();
            InfoSetting();
            lblDocumentNo.Content = Msg.Translate(Envs.GetContext(), "DocumentNo");
            lblDocumentNo.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            lblDocumentNo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDocumentNo.Margin = new Thickness(0, 0, 5, 0);

            lblBPartner_ID.Content = Msg.Translate(Envs.GetContext(), "BPartner");
            lblBPartner_ID.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            lblBPartner_ID.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblBPartner_ID.Margin = new Thickness(0, 0, 5, 0);

            lblDateFrom.Content = Msg.Translate(Envs.GetContext(), "DateTrx");
            lblDateFrom.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            lblDateFrom.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDateFrom.Margin = new Thickness(0, 0, 5, 0);

            lblDateTo.Content = "-";
            lblDateTo.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            lblDateTo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDateTo.Margin = new Thickness(0, 0, 5, 0);

            lblAmtFrom.Content = Msg.Translate(Envs.GetContext(), "PayAmt");
            lblAmtFrom.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            lblAmtFrom.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblAmtFrom.Margin = new Thickness(0, 0, 5, 0);

            lblAmtTo.Content = "-";
            lblAmtTo.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            lblAmtTo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblAmtTo.Margin = new Thickness(0, 0, 5, 0);
            //"DateFrom", false, false, true, DisplayType.Date, Msg.translate(Env.getCtx(), "DateFrom"));
            //"DateTo", false, false, true, DisplayType.Date, Msg.translate(Env.getCtx(), "DateTo"));
            //"AmtFrom", false, false, true, DisplayType.Amount, Msg.translate(Env.getCtx(), "AmtFrom"));
            //"AmtTo", false, false, true, DisplayType.Amount, Msg.translate(Env.getCtx(), "AmtTo"));
            chkIsReceipt.Content = Msg.Translate(Envs.GetContext(), "IsReceipt");
            //tooltip.SetToolTip(chkIsReceipt, Msg.Translate(Envs.GetContext(), "IsReceipt"));
            chkIsReceipt.IsChecked = true;

            Lookup _value = null;

            SetBusy(true);    
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _value = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 3499, DisplayType.Search);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(_value));
            });




            Grid.SetColumn(lblDocumentNo, 0);
            Grid.SetRow(lblDocumentNo, 0);
            this.tablePanel.Children.Add(lblDocumentNo);


            Grid.SetColumn(txtDocumentNo, 1);
            Grid.SetRow(txtDocumentNo, 0);
            this.tablePanel.Children.Add(txtDocumentNo);

            Grid.SetColumn(lblBPartner_ID, 2);
            Grid.SetRow(lblBPartner_ID, 0);
            this.tablePanel.Children.Add(lblBPartner_ID);



            Grid.SetColumn(chkIsReceipt, 5);
            Grid.SetRow(chkIsReceipt, 0);
            this.tablePanel.Children.Add(chkIsReceipt);

            Grid.SetColumn(lblDateFrom, 2);
            Grid.SetRow(lblDateFrom, 1);
            this.tablePanel.Children.Add(lblDateFrom);

            dtpDateFrom.Height = HEIGHT;
            Grid.SetColumn(dtpDateFrom, 3);
            Grid.SetRow(dtpDateFrom, 1);
            this.tablePanel.Children.Add(dtpDateFrom);

            Grid.SetColumn(lblDateTo, 4);
            Grid.SetRow(lblDateTo, 1);
            this.tablePanel.Children.Add(lblDateTo);

            dtpDateTo.Height = HEIGHT;
            Grid.SetColumn(dtpDateTo, 5);
            Grid.SetRow(dtpDateTo, 1);
            this.tablePanel.Children.Add(dtpDateTo);

            Grid.SetColumn(lblAmtFrom, 2);
            Grid.SetRow(lblAmtFrom, 2);
            this.tablePanel.Children.Add(lblAmtFrom);

            txtAmtFrom.Height = HEIGHT;
            Grid.SetColumn(txtAmtFrom, 3);
            Grid.SetRow(txtAmtFrom, 2);
            this.tablePanel.Children.Add(txtAmtFrom);


            Grid.SetColumn(lblAmtTo, 4);
            Grid.SetRow(lblAmtTo, 2);
            this.tablePanel.Children.Add(lblAmtTo);

            txtAmtTo.Height = HEIGHT;
            Grid.SetColumn(txtAmtTo, 5);
            Grid.SetRow(txtAmtTo, 2);
            this.tablePanel.Children.Add(txtAmtTo);

            txtDocumentNo.KeyDown += new KeyEventHandler(KeyEvents);
            chkIsReceipt.Checked += new RoutedEventHandler(chkIsReceipt_Checked);
            chkIsReceipt.Unchecked += new RoutedEventHandler(chkIsReceipt_Checked);
            dtpDateFrom.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dtpDateFrom_SelectedDateChanged);
            dtpDateTo.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dtpDateTo_SelectedDateChanged);

            txtAmtFrom.TextChanged += new TextChangedEventHandler(txtAmtFrom_TextChanged);
            txtAmtTo.TextChanged += new TextChangedEventHandler(txtAmtTo_TextChanged);
            txtDocumentNo.TextChanged += new TextChangedEventHandler(txtDocumentNo_TextChanged);
            vdgvRecords.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(vdgvRecords_AutoGeneratingColumn);
        }

        void txtDocumentNo_TextChanged(object sender, TextChangedEventArgs e)
        {
            _documentNo = txtDocumentNo.Text.Trim();
        }

        private void InvoKFunction(Lookup _value)
        {
            vBPartner_ID = new VTextBoxButton("C_BPartner_ID", false, false, true, DisplayType.Search, _value);

            vBPartner_ID.Height = HEIGHT;
            Grid.SetColumn(vBPartner_ID, 3);
            Grid.SetRow(vBPartner_ID, 0);
            this.tablePanel.Children.Add(vBPartner_ID);

            Context ctx = Envs.GetContext();
            String bp = ctx.GetContext(_WindowNo, "C_BPartner_ID");
            if (bp != null && bp.Length != 0)
            {
                vBPartner_ID.SetValue(bp);
            }

            var count = 0;
            if (vdgvRecords.ItemsSource != null)
            {
                count = vdgvRecords.ItemsSource.OfType<object>().Count();
            }
            base.SetStatusMsg(count.ToString() + " " + Msg.GetMsg(Envs.GetContext(), "SearchRows_EnterQuery", true));
            if (_queryValue != null && _queryValue.Length > 0)
            {
                txtDocumentNo.Text = _queryValue.ToString();
                ExecuteQuery();
            }
            _LoadedOK = true;
            txtDocumentNo.Focus();
            SetBusy(false);    
        }


        void txtAmtTo_TextChanged(object sender, TextChangedEventArgs e)
        {
            _AmtToCheck = true;
            amtTo = txtAmtTo.Text.Trim();
        }

        void txtAmtFrom_TextChanged(object sender, TextChangedEventArgs e)
        {
            _AmtFromCheck = true;
            amtFrom = txtAmtFrom.Text.Trim();
        }

        void dtpDateTo_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _dateTimeToCheck = true;
            if (dtpDateTo.Text.Trim() != "")
            {
                dateTo = Convert.ToDateTime(dtpDateTo.Text.Trim());
            }
            else
            {
                dateTo = null;
            }
        }

        void dtpDateFrom_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _dateTimeFromCheck = true;
            if (dtpDateFrom.Text.Trim() != "")
            {
                dateFrom = Convert.ToDateTime(dtpDateFrom.Text.Trim());
            }
            else
            {
                dateFrom = null;
            }
        }

        void chkIsReceipt_Checked(object sender, RoutedEventArgs e)
        {
            bpValue = vBPartner_ID.GetValue();
            isReceipt = (bool)chkIsReceipt.IsChecked;
            ExecuteQuery();
        }

        void KeyEvents(object sender, KeyEventArgs e)
        {
            isReceipt = (bool)chkIsReceipt.IsChecked;
            bpValue = vBPartner_ID.GetValue();
            if (e.Key == Key.Enter)
                ExecuteQuery();
        }

        private void InfoSetting()
        {
            RowDefinition row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);


            ColumnDefinition column = new ColumnDefinition();
            column.Width = new GridLength(30, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(50, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);


            column = new ColumnDefinition();
            column.Width = new GridLength(33, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(50, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(4, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);
        }


        /// <summary>
        /// General Init
        /// </summary>
        /// <returns>true, if success</returns>
        private bool InitInfo()
        {
            //  Set Defaults in invok fuction
            //Context ctx = Envs.GetContext();
            //String bp = ctx.GetContext(_WindowNo, "C_BPartner_ID");
            //if (bp != null && bp.Length != 0)
            //{
            //    vBPartner_ID.SetValue(bp);
            //}
            //  prepare table
            StringBuilder where = new StringBuilder("p.IsActive='Y'");
            if (_whereClause.Length > 0)
            {
                where.Append(" AND ").Append(Util.Replace(_whereClause, "C_Payment.", "p."));
            }
            PrepareTable("C_Payment_v p",
                where.ToString(),
                "2,3,4");
            return true;
        }

        string _documentNo = "";
        System.DateTime? dateFrom = null;
        System.DateTime? dateTo = null;
        string amtFrom = "";
        string amtTo = "";
        bool isReceipt = false;
        object bpValue = null;


        /// <summary>
        /// Construct SQL Where Clause and define parameters.
        /// (setParameters needs to set parameters)
        /// Includes first AND
        /// </summary>
        /// <returns>sql</returns>
        public override String GetSQLWhere()
        {
            StringBuilder sql = new StringBuilder();
            if (_documentNo.Length > 0)
            {
                sql.Append(" AND UPPER(p.DocumentNo) LIKE @param1");
            }
            //
            if (bpValue != null && bpValue != DBNull.Value)
            {
                sql.Append(" AND p.C_BPartner_ID=@param2");
            }

           if ((dateFrom != null || dateTo != null))
            {
                //if (dateFrom.Value.ToString() != "" || dateTo.Value.ToString() != "")
                {
                    if (!_dateTimeFromCheck && _dateTimeToCheck)
                    {
                        sql.Append(" AND TRUNC(p.DateTrx,'DD') <= @param6");
                    }
                    else if (_dateTimeFromCheck && !_dateTimeToCheck)
                    {
                        sql.Append(" AND TRUNC(p.DateTrx,'DD') >= @param5");
                    }
                    else if (_dateTimeFromCheck && _dateTimeToCheck)
                    {
                        sql.Append(" AND TRUNC(p.DateTrx,'DD') BETWEEN @param5 AND @param6");
                    }
                }
            }
            if ((!String.IsNullOrEmpty(amtFrom)) || (!string.IsNullOrEmpty(amtTo)))
            {
                if (amtFrom == "0" && amtTo == "0")
                {

                }
                else
                {
                    Decimal grantAmtFrom = Util.GetValueOfDecimal(amtFrom);
                    Decimal grantAmtTo = Util.GetValueOfDecimal(amtTo);
                    if (!_AmtToCheck && _AmtFromCheck)
                    {
                        sql.Append(" AND p.PayAmt>= @param7");
                    }
                    else if (!_AmtFromCheck && _AmtToCheck)
                    {
                        sql.Append(" AND p.PayAmt<= @param8");
                    }
                    else if (_AmtFromCheck && _AmtToCheck)
                    {
                        sql.Append(" AND p.PayAmt BETWEEN @param7 AND @param8");
                    }
                }
            }
            String Receipt = isReceipt == true ? "Y" : "N";
            sql.Append(" AND p.IsReceipt=" + "'" + Receipt + "'");
            log.Fine(sql.ToString());
            return sql.ToString();
        }


        /// <summary>
        /// Set Parameters for Query.
        /// (as defined in getSQLWhere)
        /// </summary>
        /// <param name="param">statement</param>
        /// <param name="forCount">for counting records</param>
        public override void SetParameters(out SqlParameter[] param, bool forCount)
        {
            String docNo = GetSQLText(_documentNo);
            Decimal grantAmtFrom = Util.GetValueOfDecimal(amtFrom);
            Decimal grantAmtTo = Util.GetValueOfDecimal(amtTo);

            if (bpValue != null)
            {
                bp = Util.GetValueOfInt(bpValue);
            }
            else
            {
                bp = 0;
            }

            int paramcount = 0;
            if (!(docNo.Equals("") || docNo.Equals("%")))
            {
                paramcount++;
            }
            if (!(bp.Equals("") || bp.Equals("%") || bp == 0))
            {
                paramcount++;
            }
            //becouse this contain default date
            if (_dateTimeFromCheck)
            {
                paramcount++;
            }
            if (_dateTimeToCheck)
            {
                paramcount++;
            }
            if (amtFrom == "0" && amtTo == "0")
            {
            }
            else
            {
                if (_AmtFromCheck)
                {
                    paramcount++;
                }
                if (_AmtToCheck)
                {
                    paramcount++;
                }
            }
            param = new SqlParameter[paramcount];
            int index = 0;
            //	=> Documenet Number
            if (!(docNo.Equals("") || docNo.Equals("%")))
            {
                if (!docNo.EndsWith("%"))
                {
                    docNo += "%";
                }
                param[index++] = new SqlParameter("@param1", docNo);
            }
            //	=> Busness Partner
            if (!(bp.Equals("") || bp.Equals("%") || bp == 0))
            {
                param[index++] = new SqlParameter("@param2", bp);
                log.Fine("BPartner=" + bp);
            }

            if ((dateFrom != null || dateTo != null))
            {
               // if (dateFrom.Value.ToString() != "" || dateTo.Value.ToString() != "")
                {
                    //	=> Date Ordered From
                    if (_dateTimeFromCheck)
                    {
                        param[index++] = new SqlParameter("@param5",dateFrom.Value.ToString("dd-MMM-yy"));
                    }
                    //	=> Date Ordered TO
                    if (_dateTimeToCheck)
                    {
                        param[index++] = new SqlParameter("@param6",dateTo.Value.ToString("dd-MMM-yy"));
                    }
                }
            }

            if (amtFrom == "0" && amtTo == "0")
            {
            }
            else
            {
                //	=> amount from
                if (_AmtFromCheck)
                {
                    param[index++] = new SqlParameter("@param7", grantAmtFrom);
                }
                //	=> Date Amt to
                if (_AmtToCheck)
                {
                    param[index++] = new SqlParameter("@param8", grantAmtTo);
                }
            }
        }

        /// <summary>
        /// Get SQL WHERE parameter
        /// </summary>
        /// <param name="f">field</param>
        /// <returns>sql</returns>
        private String GetSQLText(string f)
        {
            String s = f.ToUpper();
            if (!s.EndsWith("%"))
            {
                s += "%";
            }
            log.Fine("String=" + s);
            return s;
        }


        /// <summary>
        /// Zoom
        /// </summary>
        void Zoom()
        {
            log.Info("InfoPayment.zoom");
            int C_Payment_ID = Convert.ToInt32(GetSelectedRowKey());
            if (C_Payment_ID == null)
            {
                return;
            }
            Query query = new Query("C_Payment");
            query.AddRestriction("C_Payment_ID", Query.EQUAL, C_Payment_ID);
            query.SetRecordCount(1);
            int AD_WindowNo = GetAD_Window_ID("C_Payment", (bool)chkIsReceipt.IsChecked);
            //zoom (AD_WindowNo, query);
        }


        /// <summary>
        /// Has Zoom
        /// </summary>
        /// <returns>true</returns>
        bool HasZoom()
        {
            return true;
        }

        void vdgvRecords_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            foreach (DataGridColumn col in vdgvRecords.Columns)
            {
                if (col.DisplayIndex == 0 || col.DisplayIndex == 12)
                {
                    col.Visibility = Visibility.Collapsed;
                }
            }
        }

        protected override void bRefresh_Click(object sender, RoutedEventArgs e)
        {
            isReceipt = (bool)chkIsReceipt.IsChecked;
            bpValue = vBPartner_ID.GetValue();
            ExecuteQuery();
        }
    }
}
